package com.xxx.springboot.service.impl;

import com.xxx.springboot.pojo.bean.Product;
import com.xxx.springboot.service.ProductService;
import io.redisearch.Document;
import io.redisearch.Query;
import io.redisearch.SearchResult;
import io.redisearch.client.Client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private Client client;

    // 添加文档
    public boolean addProduct(Product product) {
        Document doc = new Document("product:" + product.getId())
                .set("title", product.getTitle())
                .set("price", product.getPrice())
                .set("category", product.getCategory())
                .set("location", product.getLocation().getLongitude() + "," + product.getLocation().getLatitude());
        return client.addDocument(doc);
    }

    // 更新文档
    public boolean updateProduct(String id, Double score, Map<String, Object> fields) {
        return client.updateDocument("product:" + id, score, fields);
    }

    // 删除文档
    public boolean deleteProduct(String id) {
        return client.deleteDocument("product:" + id);
    }

    // 基础搜索
    public SearchResult searchProducts(String query) {
        return client.search(
                new Query(query)
                        .limit(0, 10)     // 分页
                        .setWithScores()              // 返回相关性评分
        );
    }

    public SearchResult searchProductsByQuery(Query query) {
        return client.search(query);
    }
}

